package com.gwsdk.paysdk.Geetest;

import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public final class NetRequestUtils {

    private static final String TAG = "NetRequestUtils";

    private NetRequestUtils() {
    }

    private static OkHttpClient okHttpClient;

    static {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new PersistenceCookieJar())
//                .sslSocketFactory(sslContext.getSocketFactory())
                .addNetworkInterceptor(logInterceptor)
                .build();
    }


    public static String requestGet(String urlString) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(urlString).newBuilder();
        urlBuilder.addQueryParameter("t", System.currentTimeMillis() + "");
        urlBuilder.addQueryParameter("game_id", System.currentTimeMillis() + "");
        urlBuilder.addQueryParameter("sdk_version","1");
        Request request = new Request.Builder().url(urlBuilder.build()).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    private static class PersistenceCookieJar implements CookieJar {
        List<Cookie> cache = new ArrayList<>();

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            cache.addAll(cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> invalidCookies = new ArrayList<>();
            List<Cookie> validCookies = new ArrayList<>();
            for (Cookie cookie : cache) {
                if (cookie.expiresAt() < System.currentTimeMillis()) {
                    invalidCookies.add(cookie);
                } else if (cookie.matches(url)) {
                    validCookies.add(cookie);
                }
            }
            cache.removeAll(invalidCookies);
            return validCookies;
        }
    }

    private static class HttpLogger implements HttpLoggingInterceptor.Logger {

        @Override
        public void log(String message) {
            Log.d(TAG, "Logger: " + message);
        }
    }

}
